package cn.shop.gateway.view;


import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.db.Entity;
import cn.shop.gateway.Config;
import cn.shop.gateway.db.DbUtil;
import cn.shop.gateway.utils.ResponseInfo;
import cn.shop.gateway.utils.WatchUtil;
import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author : 李一涵
 * @date : Created in 2021-12-16 17:28
 * @description :
 */
public class RootLayoutController {

    private final static Logger LOG = LoggerFactory.getLogger(RootLayoutController.class);

    @FXML
    private Label allCount;
    @FXML
    private Label successCount;
    @FXML
    private Label failCount;
    @FXML
    private TextField search;
    @FXML
    private Label result;
    @FXML
    private TextField port;

    public void setAllCount(long count) {
        long c = Long.parseLong(allCount.getText());
        allCount.setText(Long.toString(c + count));
    }

    public void setSuccessCount(long count) {
        long c = Long.parseLong(successCount.getText());
        successCount.setText(Long.toString(c + count));
    }

    public void setFailCount(long count) {
        long c = Long.parseLong(failCount.getText());
        failCount.setText(Long.toString(c + count));
    }

    public void clearFailCount() {
        failCount.setText(Long.toString(0));
    }

    public long getAllCount() {
        return Long.parseLong(allCount.getText());
    }

    public long getSuccessCount() {
        return Long.parseLong(successCount.getText());
    }

    public long getFailCount() {
        return Long.parseLong(failCount.getText());
    }

    public void setPort(String p) {
        port.setText(p);
    }
    @FXML
    public void searchOrder() throws SQLException {
        String id = search.getText();
        if (StrUtil.isBlank(id)) {
            return;
        }
        Entity order = DbUtil.getOrderCheck(id);
        if (order == null || StrUtil.isBlank(order.getStr("time"))) {
            result.setText("无下发时间");
        } else {
            result.setText("下发时间" + order.getStr("time"));
        }
    }

    @FXML
    public void resendOrder() {
        LOG.info("开始重发");
        List<Entity> lines = DbUtil.getFailOrders();
        LOG.info("list {}", lines);
        if (!lines.isEmpty()) {
            ResponseInfo<Object> result;
            clearFailCount();
            for (Entity line : lines) {
                String folder = line.getStr("folder");
                List<String> orders = Arrays.asList(line.getStr("json").split("#"));
                try {
                    result = WatchUtil.sendOrder(orders, folder);
                    if (result != null && result.getCode() == 1) {
                        setSuccessCount(1);
                    } else {
                        setFailCount(1);
                        DbUtil.saveFailOrder(folder, orders);
                    }
                } catch (Exception e) {
                    setFailCount(1);
                    DbUtil.saveFailOrder(folder, orders);
                    LOG.error("发送订单出错: {} {}", folder, orders, e);
                }
            }
        }
    }

    public Map<String, List<Entity>> format(List<Entity> entities) {
        return entities.stream().collect(Collectors.groupingBy(entity -> entity.getStr("folder")));
    }

    @FXML
    public void updatePort() {
        String text = port.getText();
        if (text == null || text.isEmpty() || !NumberUtil.isInteger(text) || NumberUtil.parseInt(text) <= 0) {
            return;
        }
        if(text.equals(Config.getString("server.port"))) {
            return;
        }
        Config.setPort(text);
        Config.store();
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle("提示");
        alert.setHeaderText("修改成功, 请重启网关");
        //alert.setContentText("重新启动网关新端口才会生效");
        alert.showAndWait();
    }
}
